package com.itheima.admin.contorller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.exception.MyException;
import com.itheima.common.result.JsonResult;
import com.itheima.entity.Employee;
import com.itheima.entity.vo.EmployeeVo;
import com.itheima.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author : sky
 * @date : 2023/3/2 21:20
 * @modyified By :
 */
@RequestMapping("employee")
@RestController
@Api(tags = "员工管理")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 员工登陆
     *
     * @return
     */
    @PostMapping("login")
    @ApiOperation(value = "员工登陆")
    public JsonResult empLogin(@RequestBody Employee employee){
        //判断用户名和密码是否存在
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername,employee.getUsername());
        wrapper.eq(Employee::getPassword,employee.getPassword());
        Employee emp = employeeService.getOne(wrapper);
        if (null==emp){
            System.out.println("用户名或者密码错误！");
        }
        //用户存在，生成token
        String token = JWT.create().setPayload("id", employee.getId())
                .setPayload("time", System.currentTimeMillis())
                .setKey("1234".getBytes(StandardCharsets.UTF_8))
                .sign();
        //token存入reids
        redisTemplate.opsForValue().set(token, "1", 3600, TimeUnit.SECONDS);
        //封装前端对象，去除敏感信息,添加token
        EmployeeVo employeeVo = new EmployeeVo();
        BeanUtil.copyProperties(employeeVo, employeeVo);
        employeeVo.setToken(token);
        //返回结果
        return JsonResult.success(employeeVo);
    }
    /**
     * 员工登出
          */
    @PostMapping("logout")
    @ApiOperation(value = "员工登出")
    public JsonResult empLoginout(String token){
    //判断token是否存在
        if (null==redisTemplate.hasKey(token)){
            System.out.println(token+"已经过期");
            throw new MyException(404, "token不存在");
        }
       //存在，直接删除
        redisTemplate.delete(token);
        return JsonResult.success("用户登出成功！");
    }
@PostMapping
@ApiOperation(value = "添加员工")
 public JsonResult addEmp(@RequestBody Employee employee){
  employeeService.save(employee);
  return JsonResult.success("添加成功！");
}
@PutMapping
@ApiOperation(value = "根据状态修改或者禁用员工")
public JsonResult updateEmp(@RequestBody Employee employee){
        //判断数据库是否存在数据
    LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Employee::getUsername,employee.getUsername());
    Employee employeeone = employeeService.getOne(wrapper);
    if (null==employeeone){
        throw new MyException(400, "用户不存在");
    }
        //查询修改状态是不是“0”
       if ("0".equals(employeeone.getStatus())){
           throw new MyException(403, "用户不允许修改");
       }
       //不是“0”修改状态
    LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
       updateWrapper.eq(Employee::getId,employee.getId());
       employeeService.update(employee, wrapper);
       return JsonResult.success("修改成功");
}
/***查询员工信息
 *
 * @return*/
@GetMapping("{id}")
@ApiOperation("查询员工信息")
   public JsonResult getEmpById(@PathVariable String id ){
    LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Employee::getId, id);
    Employee employee = employeeService.getOne(wrapper);
    return JsonResult.success(employee);

}
/**
 * 查询分页信息
 *
 * @return
 */
@GetMapping("page")
@ApiOperation(value = "分页展示员工信息")
    public JsonResult getEmpInfoBypage(
            String name,
           @RequestParam   Integer page,
           @RequestParam Integer pageSize
){
    Page<Employee> page1 = new Page<>(page, pageSize);
    LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Employee::getName,name);
    Page<Employee> employeePage = employeeService.page(page1, wrapper);
    return JsonResult.success(employeePage);
}
}
